package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author lwm
 * @since 2022-02-10
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerService borrowerService;
    @Resource
    private LendService lendService;

    //提交借款申请，添加记录
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null) {
            return;
        }
        //判断用户的第三方资金账户绑定状态
        Assert.equals(userInfo.getBindStatus(), UserBindEnum.BIND_OK.getStatus(),
                ResponseEnum.USER_NO_BIND_ERROR);
        //判断借款人额度的审核状态
        Assert.equals(userInfo.getBorrowAuthStatus(), BorrowerStatusEnum.AUTH_OK.getStatus(),
                ResponseEnum.USER_NO_AMOUNT_ERROR);
        //判断借款人额度是否充足
        BigDecimal borrowAmount = userInfoService.getBorrowAmount(userId);
        Assert.isTrue(borrowAmount.compareTo(borrowInfo.getAmount()) >= 0,
                ResponseEnum.USER_AMOUNT_LESS_ERROR);
        //设置借款申请的userId
        borrowInfo.setUserId(userId);
        //设置借款申请的年化利率--百分比转为小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate()
                .divide(new BigDecimal("100"), 3, RoundingMode.HALF_UP));
        //设置借款申请的审核状态--审核中
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());

        baseMapper.insert(borrowInfo);
    }

    //获取借款申请的审批状态
    @Override
    public Integer getStatusByUserId(Long userId) {
        LambdaQueryWrapper<BorrowInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BorrowInfo::getUserId, userId)
                .select(BorrowInfo::getStatus);
        BorrowInfo borrowInfo = baseMapper.selectOne(wrapper);
        Integer status = BorrowInfoStatusEnum.NO_AUTH.getStatus();
        if (borrowInfo != null) {
            status = borrowInfo.getStatus();
        }
        return status;
    }

    //借款信息列表
    @Override
    public List<BorrowInfo> selectList() {
        //联合borrower表查询所有BorrowInfo记录
        List<BorrowInfo> borrowInfoList = baseMapper.listUnionBorrower();
        //给borrowInfoList中的param集合添加对应的字典文本和状态文本
        setDictText(borrowInfoList);
        return borrowInfoList;
    }

    //获取借款申请的详情和借款人的详情
    @Override
    public Map<String, Object> getBorrowInfoAndBorrowerDetail(Long borrowInfoId) {
        //查询borrowInfo，包括封装文本信息
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        setDictText(borrowInfo);

        //根据user_id获取borrowerDetailVO
        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper<Borrower>()
                .eq(Borrower::getUserId, borrowInfo.getUserId());
        Borrower borrower = borrowerService.getOne(wrapper);
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetail(borrower.getId());
        //组装数据
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo", borrowInfo);
        result.put("borrower", borrowerDetailVO);
        return result;
    }

    //审批借款申请，根据审核信息创建标的
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        //获取borrowInfo
        Long borrowInfoId = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        //更新borrowInfo的审批状态
        Integer status = borrowInfoApprovalVO.getStatus();
        borrowInfo.setStatus(status);
        baseMapper.updateById(borrowInfo);
        //如果审核通过创建标的
        if (status.equals(BorrowInfoStatusEnum.CHECK_OK.getStatus())){
            //创建标的
            lendService.creatLend(borrowInfoApprovalVO, borrowInfo);
        }
    }

    //添加对应的字典文本和状态文本
    private void setDictText(List<BorrowInfo> borrowInfoList) {
        for (BorrowInfo borrowInfo : borrowInfoList) {
            Map<String, Object> param = borrowInfo.getParam();
            param.put("returnMethod", dictService.getText("returnMethod",
                    borrowInfo.getReturnMethod()));
            param.put("moneyUse", dictService.getText("moneyUse",
                    borrowInfo.getMoneyUse()));
            param.put("status", BorrowerStatusEnum.
                    getMsgByStatus(borrowInfo.getStatus()));
        }
    }

    //添加对应的字典文本和状态文本(单个)
    private void setDictText(BorrowInfo borrowInfo) {
        Map<String, Object> param = borrowInfo.getParam();
        param.put("returnMethod", dictService.getText("returnMethod",
                borrowInfo.getReturnMethod()));
        param.put("moneyUse", dictService.getText("moneyUse",
                borrowInfo.getMoneyUse()));
        param.put("status", BorrowerStatusEnum.
                getMsgByStatus(borrowInfo.getStatus()));

    }
}
